#!/usr/bin/python
# -*- coding: utf-8 -*-

#DEpendencies PACKage V0.95

############################################################################
#    Copyright (C) 2007-2010 by Zolotarevsky Alexander (ALex-AnNet)        #
#                                                                          #
#                          alex7annet@gmail.com                            #
#                                                                          #
#    This program is free software; you can redistribute it and#or modify  #
#    it under the terms of the GNU General Public License as published by  #
#    the Free Software Foundation; either version 2 of the License, or     #
#    (at your option) any later version.                                   #
#                                                                          #
#    This program is distributed in the hope that it will be useful,       #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of        #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         #
#    GNU General Public License for more details.                          #
#                                                                          #
#    You should have received a copy of the GNU General Public License     #
#    along with this program; if not, write to the                         #
#    Free Software Foundation, Inc.,                                       #
#    59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             #
############################################################################

import types
import os
import sys
import tempfile
import re
import getopt
import signal
from random import *

sys.path.append('/usr/share/depack')

#sys.path.append('/home/alex/projects/myProject/depack/depack-encore')

from depack.verlib   import *
from depack.toolib   import *

class MyError(Exception) : pass

signal.signal(signal.SIGINT, SigStop)
signal.signal(signal.SIGTERM, SigStop)



mesdic = {}

mesdic['mes_no_ebuild']          = "no ebuilds"
mesdic['mes_no_files']           = "no files"
mesdic['mes_package_no_files']   = "package: no files"
mesdic['mes_create_table']       = "Created table"
mesdic['mes_add_table']          = "Add table"
mesdic['mes_exits_table']        = "Table already exist"
mesdic['mes_err_del_table']      = "Deleted table"
mesdic['mes_mediums_program']    = "Others mediums with Absences files:"
mesdic['mes_delete']             = "delete:"
mesdic['mes_set']                = "set:"
mesdic['mes_no_uses']            = "No uses"
mesdic['mes_create_file']        = "Create file:"
mesdic['mes_mediums']            = "All mediums:"
mesdic['mes_files']              = "files"
mesdic['mes_all']                = "ALL:"
mesdic['mes_ex']                 = "Existances:"
mesdic['mes_ab']                 = "Absences:"
mesdic['mes_set_arch']           = "set architecture in config"
mesdic['mes_err']                = "error:"
mesdic['mes_err_syntax']         = "error: syntax"
mesdic['mes_err_unknown_sect']   = "error: unknown section"
mesdic['mes_err_not_sect']       = "error: not found section for"
mesdic['mes_err_not_found']      = "error: not found variable"
mesdic['mes_err_ambiguity']      = "error: add category"
mesdic['mes_err_root']           = "error: operation only for root"
mesdic['mes_err_bad']            = "error: bad key"
mesdic['mes_err_dist']           = "error: variable 'distfiles' is empty"
mesdic['mes_err_dist_config']    = "error: variable 'distfiles' definite incorrect"
mesdic['mes_err_title']          = "error: this table already exist"
mesdic['mes_err_file']           = "error: file don't open"
mesdic['mes_err_file_create']    = "error: file don't create"
mesdic['mes_err_assoc']          = "error: directory isn't existence"
mesdic['mes_err_bad_table']      = "error: bad table"
mesdic['mes_err_dont_ex_table']  = "error: table don't exist"
mesdic['mes_err_inst_getdelta']  = "error: install getdelta"
mesdic['mes_err_add_version']    = "error: add version"
mesdic['mes_err_del_version']    = "error: delete version"
mesdic['mes_err_sign']           = "error: in '<,>,='"
mesdic['mes_err_init_arch']      = "error: add your architecture in config or run as root 'depack --set-arch <your architecture>'"
mesdic['mes_err_def_colorize']   = "error: variable 'colorize' definite incorrect"
mesdic['mes_err_def_info']       = "error: variable 'info' definite incorrect"
mesdic['mes_err_key']            = "error: contradictories keys"
mesdic['mes_err_config']         = "error: config don't open"
mesdic['mes_err_not_found_var']  = "error: not found variable:"
mesdic['mes_err_set_arch']       = "error: variable 'arch' not found"
mesdic['mes_err_not_arg']        = "error: not arguments"
mesdic['mes_err_name_var']       = "error: name variable"
mesdic['mes_err_not_enough']     = "error: not enough arguments"
mesdic['mes_err_unknown_var']    = "error: unknown variable"

mes_help = ""




calc_dep = 1

out_dep = 1

left = 0

right = 0

create_table = 0

delete_table = 0

list_tables = 0

copy_files = 0

mnt = 0

getdelta = 0

keywords = 0

fastkw = 0

mask = 0

print_uses = 0

uses = 0

null = 0

exists = 0

iscolor = 1

add_table = 0

template = 0

path_kw = 0

path_m = 0

path_u = 0

path_f = 0

path_d = 0

arch_f = 0

ex_flag = 0

pl_flag = 0

info_flag = 0

fl_set_arch = 0

simple = 0

help = 0




class mount:
   name = "mount"
   colp = 2
   var = {}
   list_var = {}
   check_var = False
#class mount

mount = mount()

class templates:
   name = "templates"
   colp = 2
   var = {}
   list_var = {}
   check_var = False
#class templates

templates = templates()

class general:
   name = "general"
   colp = 1
   var = {}
   list_var = {'colorize':None,'arch':None,'existence':None,'place':None,'info':None,'locale':None}
   check_var = True
#class general

general = general()

class paths:
   name = "paths"
   colp = -1
   var = {}
   list_var = {'files':None,'masks':None,'uses':None,'keywords':None}
   check_var = True
#class paths

paths = paths()

try:
   file_config = open(config)

except:
   print mesdic['mes_err_config']
   sys.exit(2)


file_inv_box = []

file_box = []


str_file = file_config.readline()
for str_file in file_config:
   str_check = str_file.split(comment)
   if str_check[0].strip() != "":
      file_inv_box.append(str_file)


for i in file_inv_box:
   file_box.append(i)


arg = "null"
colp = 0
cur_sect = "null"
for str_file in file_box:
   if str_file.strip() == "":
      pass
   elif find_section(str_file.strip().lower()) != "null":
      cur_sect = find_section(str_file)
   else:
      if cur_sect == "[mount]":
         arg_colp = treatment_str(str_file, mount, colp, arg, mesdic)
         arg  = arg_colp[0]
         colp = arg_colp[1]
         if arg == "":
            sys.exit(2)

      elif cur_sect == "[templates]":
         arg_colp = treatment_str(str_file, templates, colp, arg, mesdic)
         arg  = arg_colp[0]
         colp = arg_colp[1]
         if arg == "":
            sys.exit(2)

      elif cur_sect == "[general]":
         arg_colp = treatment_str(str_file, general, colp, arg, mesdic)
         arg  = arg_colp[0]
         colp = arg_colp[1]
         if arg == "":
            sys.exit(2)

      elif cur_sect == "[paths]":
         check = check_str(str_file, mesdic)
         if check == 0:
            arg = "null"

         elif check == 1:
            arg = get_variable(str_file, paths.check_var, paths.list_var, mesdic)
            value = get_value(str_file)

            paths.var[arg] = value

         elif check == 2:
            if arg != "null":
               value = get_value(str_file)

               paths.var[arg] += value

      else:
         if cur_sect == "null":
            print mesdic['mes_err_not_sect'] + " '" + str_file.replace('\n', '').strip() + "'" 
         else:
            print mesdic['mes_err_unknown_sect'] + " '" + cur_sect + "'"

   str_file = file_config.readline()



portage        = '/usr/portage'
path_base      = '/var/depack/base'
#path_locale    = '/home/alex/projects/myProject/depack/depack-encore/locale'
path_locale    = '/var/depack/locale'


try:
   files_path = paths.var['files']
except:
   print mesdic['mes_err_not_found_var'] + " files"
   sys.exit(2)


try:
   path_keywords  = paths.var['keywords']
except:
   print mesdic['mes_err_not_found_var'] + " keywords"
   sys.exit(2)


try:
   path_masks     = paths.var['masks']
except:
   print mesdic['mes_err_not_found_var'] + " masks"
   sys.exit(2)


try:
   path_uses      = paths.var['uses']
except:
   print mesdic['mes_err_not_found_var'] + " uses"
   sys.exit(2)



try:
   locale      = general.var['locale'][0].lower().strip()
except:
   print mesdic['mes_err_not_found_var'] + " locale"
   sys.exit(2)

if locale == "":
   print mesdic['mes_err_not_found_var'] + " locale"
   sys.exit(2)

if locale == 'auto':


   tempf = tempfile.mktemp()

   os.system('locale  > ' + tempf)

   try:
      file = open(tempf)

   except:
      print mesdic['mes_err_file'] 

      sys.exit(2)

   str_file = file.readline()

   while str != '':

      if str_file.find('LANG=') > -1:

         str_file = str_file.lower()
         str_file = str_file.replace('-', '')

         if str_file.find('cp1251') > -1:
            locale = 'cp1251'

         if str_file.find('utf8') > -1:
            locale = 'utf8'

         if str_file.find('koi8r') > -1:
            locale = 'koi8r'

         break

      str_file = file.readline()

   file.close()

for fl in os.listdir(path_locale):

   if fl == locale:
      localef = fl
      break


if locale != 'eng':
   
   try:
      file = open(path_locale + '/' + localef)

      mesdic['mes_no_ebuild']          = file.readline().replace('\n', '')
      mesdic['mes_no_files']           = file.readline().replace('\n', '')
      mesdic['mes_package_no_files']   = file.readline().replace('\n', '')
      mesdic['mes_create_table']       = file.readline().replace('\n', '')
      mesdic['mes_add_table']          = file.readline().replace('\n', '')
      mesdic['mes_exits_table']        = file.readline().replace('\n', '')
      mesdic['mes_err_del_table']      = file.readline().replace('\n', '')
      mesdic['mes_mediums_program']    = file.readline().replace('\n', '')
      mesdic['mes_delete']             = file.readline().replace('\n', '')
      mesdic['mes_set']                = file.readline().replace('\n', '')
      mesdic['mes_no_uses']            = file.readline().replace('\n', '')
      mesdic['mes_create_file']        = file.readline().replace('\n', '')
      mesdic['mes_mediums']            = file.readline().replace('\n', '')
      mesdic['mes_files']              = file.readline().replace('\n', '')
      mesdic['mes_all']                = file.readline().replace('\n', '')
      mesdic['mes_ex']                 = file.readline().replace('\n', '')
      mesdic['mes_ab']                 = file.readline().replace('\n', '')
      mesdic['mes_set_arch']           = file.readline().replace('\n', '')
      mesdic['mes_err']                = file.readline().replace('\n', '')
      mesdic['mes_err_syntax']         = file.readline().replace('\n', '')
      mesdic['mes_err_unknown_sect']   = file.readline().replace('\n', '')
      mesdic['mes_err_not_sect']       = file.readline().replace('\n', '')
      mesdic['mes_err_not_found']      = file.readline().replace('\n', '')
      mesdic['mes_err_ambiguity']      = file.readline().replace('\n', '')
      mesdic['mes_err_root']           = file.readline().replace('\n', '')
      mesdic['mes_err_bad']            = file.readline().replace('\n', '')
      mesdic['mes_err_dist']           = file.readline().replace('\n', '')
      mesdic['mes_err_dist_config']    = file.readline().replace('\n', '')
      mesdic['mes_err_title']          = file.readline().replace('\n', '')
      mesdic['mes_err_file']           = file.readline().replace('\n', '')
      mesdic['mes_err_file_create']    = file.readline().replace('\n', '')
      mesdic['mes_err_assoc']          = file.readline().replace('\n', '')
      mesdic['mes_err_bad_table']      = file.readline().replace('\n', '')
      mesdic['mes_err_dont_ex_table']  = file.readline().replace('\n', '')
      mesdic['mes_err_inst_getdelta']  = file.readline().replace('\n', '')
      mesdic['mes_err_add_version']    = file.readline().replace('\n', '')
      mesdic['mes_err_del_version']    = file.readline().replace('\n', '')
      mesdic['mes_err_sign']           = file.readline().replace('\n', '')
      mesdic['mes_err_init_arch']      = file.readline().replace('\n', '')
      mesdic['mes_err_def_colorize']   = file.readline().replace('\n', '')
      mesdic['mes_err_def_info']       = file.readline().replace('\n', '')
      mesdic['mes_err_key']            = file.readline().replace('\n', '')
      mesdic['mes_err_config']         = file.readline().replace('\n', '')
      mesdic['mes_err_not_found_var']  = file.readline().replace('\n', '')
      mesdic['mes_err_set_arch']       = file.readline().replace('\n', '')
      mesdic['mes_err_not_arg']        = file.readline().replace('\n', '')
      mesdic['mes_err_name_var']       = file.readline().replace('\n', '')
      mesdic['mes_err_not_enough']     = file.readline().replace('\n', '')
      mesdic['mes_err_unknown_var']    = file.readline().replace('\n', '')

      file.close()

   except:
      pass




pref = ""

post = ""

dist_path = []

title = ""

assoc = ""

addtable = ""

is_file_sign   = '+'

isnt_file_sign = '-'

device = ""

mpoint = ""

try:
   arch = general.var['arch'][0]
except:
   print mesdic['mes_err_not_found_var'] + " arch"
   sys.exit(2)


sign_kw = ""

sign_mask = ""

veb_use = ""

try:
   color = general.var['colorize'][0].lower()
except:
   print mesdic['mes_err_not_found_var'] + " colorize"
   sys.exit(2)


flags = ""

try:
   out_ex = general.var['existence'][0].lower()
except:
   print mesdic['mes_err_not_found_var'] + " existence"
   sys.exit(2)


try:
   out_pl = general.var['place'][0].lower()
except:
   print mesdic['mes_err_not_found_var'] + " place"
   sys.exit(2)


set_arch = ""



pack_keyw = 0

pack_mask = 0

pack_uses = 0

make_glob = 0




if len(sys.argv) == 1:

   if color.lower().strip() == "true":
      
      mes_name = ""
      mes_name += SetColor("turquoise","DE",iscolor)
      mes_name += SetColor("teal","5nd@nciz",iscolor)
      mes_name += " "
      mes_name += SetColor("turquoise","PACK",iscolor)
      mes_name += SetColor("teal", "_ag",iscolor)
      mes_name += " "
      mes_name += SetColor("turquoise", "V",iscolor)
      mes_name += SetColor("teal", "0",iscolor)
      mes_name += SetColor("turquoise", ".95",iscolor)

      print mes_name

      sys.exit(0)




short_key = 'k:K:m:H:U:l:r:d:T:C:M:a:p:u:s:ALDcgfneSNh'

long_key = ['keywords=','path_keyw=','mask=','path_mask=','path_use=','left=','right=','dist=',
            'template=','create_table=','mount=','architecture=','path=','uses=','set=','add-table',
            'list-table','delete-table','copy','getdelta','fast-arch','null','existence','simple',
            'no_color', 'help', 'set-arch']


try:
   var, arg = getopt.getopt(sys.argv[1:], short_key, long_key)

except:
   print mesdic['mes_err_bad']

   sys.exit(2)


for i in var:

   
   if i[0] == '-h':
      help = 1

   elif i[0] == '--help':
      help = 1

   
   elif i[0] == '-l':
      pref = i[1].replace(':', '')
      left = 1

   elif i[0] == '--left':
      pref = i[1]
      left = 1

   
   elif i[0] == '-r':
      post = i[1].replace(':', '')
      right = 1

   elif i[0] == '--right':
      post = i[1]
      right = 1

   
   elif i[0] == '--set-arch':
      set_arch = arg[0]
      fl_set_arch = 1

   
   elif i[0] == '-e':
      exists = 1

   elif i[0] == '--existence':
      exists = 1

   
   elif i[0] == '-n':
      null = 1

   elif i[0] == '--null':
      null = 1

   
   elif i[0] == '-N':
      color = "false"

   elif i[0] == '--no_color':
      color = "false"

   
   elif i[0] == '-S':
      out_ex = "false"
      out_pl = "false"
      simple = 1

   elif i[0] == '--simple':
      out_ex = "false"
      out_pl = "false"
      simple = 1

   
   elif i[0] == '-U':

      path_uses = [i[1].replace(':', '')]
      path_u = 1

   elif i[0] == '--path_use':

      path_uses = [i[1]]
      path_u = 1

   
   elif i[0] == '-s':

      calc_dep = 0
      out_dep = 0
      uses = 1
      flags = i[1].replace(':', '')

   elif i[0] == '--set':

      calc_dep = 0
      out_dep = 0
      uses = 1
      flags = i[1]  

   
   elif i[0] == '-u':
      try:
         veb_use  = i[1].replace(':', '')
      except:
         print mesdic['mes_err_bad']
         sys.exit(2)

      print_uses = 1
      calc_dep = 0
      out_dep = 0

   elif i[0] == '--uses':
      try:
         veb_use  = i[1]
      except:
         print mesdic['mes_err_bad']
         sys.exit(2)

      print_uses = 1
      calc_dep = 0
      out_dep = 0

   
   elif i[0] == '-H':

      path_masks = [i[1].replace(':', '')]
      path_m = 1

   elif i[0] == '--path_mask':

      path_masks = [i[1]]
      path_m = 1

   
   elif i[0] == '-m':

      is_root(mesdic)

      calc_dep = 0
      out_dep = 0
      mask = 1
      sign_mask = i[1].replace(':', '')
 
   elif i[0] == '--mask':

      is_root(mesdic)

      calc_dep = 0
      out_dep = 0
      mask = 1
      sign_mask = i[1]

   
   elif i[0] == '-K':

      path_keywords = [i[1].replace(':', '')]
      path_kw = 1

   elif i[0] == '--path_keyw':

      path_keywords = [i[1]]
      path_kw = 1

   
   elif i[0] == '-f':

      is_root(mesdic)

      calc_dep = 0
      out_dep = 0
      sign_kw = '-'
      fastkw = 1

   elif i[0] == '--fast-arch':

      is_root(mesdic)

      calc_dep = 0
      out_dep = 0
      sign_kw = '-'
      fastkw = 1

   
   elif i[0] == '-k':

      is_root(mesdic)

      calc_dep = 0
      out_dep = 0
      sign_kw = i[1].replace(':', '')
      keywords = 1

   elif i[0] == '--keywords':

      is_root(mesdic)

      calc_dep = 0
      out_dep = 0
      sign_kw = i[1]
      keywords = 1

   
   elif i[0] == '-a':

      is_root(mesdic)

      calc_dep = 0
      out_dep = 0
      arch = i[1].replace(':', '')
      arch_f = 1

   elif i[0] == '--architecture':

      is_root(mesdic)

      calc_dep = 0
      out_dep = 0
      arch = i[1]
      arch_f = 1

   
   elif i[0] == '-d':
      dist_path.append(i[1].replace(':', ''))
      path_d = 1

   elif i[0] == '--dist':
      dist_path.append(i[1])
      path_d = 1

   
   elif i[0] == '-p':
      files_path.append(i[1].replace(':', ''))
      path_f = 1

   elif i[0] == '--path':
      files_path.append(i[1])
      path_f = 1

   
   elif i[0] == '-T':
      try:
         if left == 0:
            pref = templates.var[i[1].replace(':', '')][0]
            left = 1

         if right == 0:
            post = templates.var[i[1].replace(':', '')][1]
            right = 1

      except:
         print mesdic['mes_err_not_found'] + " " + i[1].replace(':', '')
         sys.exit(2)

      template = 1

   elif i[0] == '--template':
      try:
         if left == 0:
            pref = templates.var[i[1]][0]
            left = 1

         if right == 0:
            post = templates.var[i[1]][1]
            right = 1

      except:
         print mesdic['es_err_not_found'] + " " + i[1]
         sys.exit(2)

      template = 1

   
   elif i[0] == '-C':
      is_root(mesdic)

      if len(arg) != 1:
         print mesdic['mes_err_bad']
         sys.exit(2)

      try:
         title  =  arg[0]
      except:
         print mesdic['mes_err_bad']
         sys.exit(2)

      calc_dep = 0
      out_dep = 0
      create_table = 1
      assoc = i[1].replace(':', '')

   elif i[0] == '--create_table':
      is_root(mesdic)

      try:
         title  =  arg[0]
      except:
         print mesdic['mes_err_bad']
         sys.exit(2)

      calc_dep = 0
      out_dep = 0
      create_table = 1
      assoc = i[1]

   
   elif i[0] == '-A':
      is_root(mesdic)

      if len(arg) != 1:
         print mesdic['mes_err_bad']
         sys.exit(2)

      try:
         addtable = arg[0]
      except:
         print mesdic['mes_err_bad']
         sys.exit(2)  

      add_table = 1
      calc_dep = 0
      out_dep = 0

   elif i[0] == '--add-table':
      is_root(mesdic)

      try:
         addtable = arg[0]
      except:
         print mesdic['mes_err_bad']
         sys.exit(2)  

      add_table = 1
      calc_dep = 0
      out_dep = 0

   
   elif i[0] == '-L':

      if len(arg) > 0:
         print mesdic['mes_err_bad']

         sys.exit(2)

      list_tables = 1
      calc_dep = 0
      out_dep = 0

   elif i[0] == '--list-table':

      if len(arg) > 0:
         print mesdic['mes_err_bad']

         sys.exit(2)

      list_tables = 1
      calc_dep = 0
      out_dep = 0

   
   elif i[0] == '-D':

      is_root(mesdic)

      if len(arg) != 1:
         print mesdic['mes_err_bad']
         sys.exit(2)

      try:
         title  =  arg[0]
      except:
         print mesdic['mes_err_bad']
         sys.exit(2)

      create_table = 0
      delete_table = 1
      calc_dep = 0
      out_dep = 0

      if title.strip() == '*':
         list_tables = 1

   elif i[0] == '--delete-table':

      is_root(mesdic)
      try:
         title  = arg[0]
      except:
         print mesdic['mes_err_bad']
         sys.exit(2)

      create_table = 0
      delete_table = 1
      calc_dep = 0
      out_dep = 0

      if title.strip() == '*':
         list_tables = 1

   
   elif i[0] == '-c':
      copy_files = 1
      out_dep = 0

   elif i[0] == '--copy':
      copy_files = 1
      out_dep = 0

   
   elif i[0] == '-M':
      mnt  = 1
      try:
         device = mount.var[i[1].replace(':', '')][0]
         mpoint = mount.var[i[1].replace(':', '')][1]

      except:
         print mesdic['mes_err_not_found'] + " " + i[1].replace(':', '')
         sys.exit(2)

   elif i[0] == '--mount':
      mnt = 1
      try:
         device = mount.var[i[1]][0]
         mpoint = mount.var[i[1]][1]

      except:
         print mesdic['mes_err_not_found'] + " " + i[1]
         sys.exit(2)

   
   if i[0] == '-g':
      getdelta = 1
      out_dep = 0

   elif i[0] == '--getdelta':
      getdelta = 1
      out_dep = 0




work_packages = []

if calc_dep == 1:
   
   for j in arg:
      work_packages.append(j)

elif keywords == 1:
   
   for j in arg:
      work_packages.append(j)

elif fastkw == 1:
   
   for j in arg:
      work_packages.append(j)

elif mask == 1:
   
   for j in arg:
      work_packages.append(j)

elif uses == 1:
   
   for j in arg:
      work_packages.append(j)


if   color.lower().strip() == "true":
   iscolor = 1
elif color.lower().strip() == "false":
   iscolor = 0
else:
   print mesdic['mes_err_def_colorize']
   sys.exit(2)


if   out_ex.lower().strip() == "true":
   ex_flag = 1
elif out_ex.lower().strip() == "false":
   ex_flag = 0
else:
   print mesdic['mes_err_def_colorize']
   sys.exit(2)


if   out_pl.lower().strip() == "true":
   pl_flag = 1
elif out_pl.lower().strip() == "false":
   pl_flag = 0
else:
   print mesdic['mes_err_def_colorize']
   sys.exit(2)


try:
   info_var = general.var['info'][0]
except:
   print mesdic['mes_err_not_found_var'] + " info"
   sys.exit(2)

if   info_var.lower().strip() == "true":
   info_flag = 1
elif info_var.lower().strip() == "false":
   info_flag = 0
else:
   print mesdic['mes_err_def_info']
   sys.exit(2)



#-m(mask) -s(uses) -f(fastkw)/-k(keywords)
#-C(create_table) -A(add_table) -L(list_tables): -D(delete_table) -u(print_uses): -c(copy_files) -g(getdelta)


#-K(path_kw) -H(path_m) -U(path_u) -p(path_f) -d(path_d) -a(arch_f) -N(iscolor) -S(out_pl,out_ex)

#-l(left) -r(right) -T(template) -M(mnt) -n(null) -e(exists)

#-h




action  = (keywords + mask + create_table + print_uses + uses + add_table + list_tables + delete_table)
action += (copy_files + getdelta + fastkw)


if len(work_packages) == 0:
   if   list_tables == 1:
      pass
   elif print_uses == 1:
      pass
   elif create_table == 1:
      pass
   elif add_table == 1:
      pass
   elif delete_table == 1:
      pass
   elif fl_set_arch == 1:
      pass
   elif help == 1:
      pass
   else:
      print mesdic['mes_err_key']
      sys.exit(2)


if action > 1:
   if help == 0:
      if list_tables == 1:
         if delete_table == 1:
            pass
         else:
            print mesdic['mes_err_key']
            sys.exit(2)
      else:
         print mesdic['mes_err_key']
         sys.exit(2)
   else:
      print mesdic['mes_err_key']
      sys.exit(2)



if help == 1:
   if action > 0:
      print mesdic['mes_err_key']
      sys.exit(2)

if fl_set_arch == 1:
   if action > 0:
      print mesdic['mes_err_key']
      sys.exit(2)

if arch_f == 1:
   if action == 0:
      print mesdic['mes_err_key']
      sys.exit(2)

if left == 1:
   if action > 0:
      print mesdic['mes_err_key']
      sys.exit(2)

if right == 1:
   if action > 0:
      print mesdic['mes_err_key']
      sys.exit(2)

if template == 1:
   if action > 0:
      print mesdic['mes_err_key']
      sys.exit(2)

if mnt == 1:
   if copy_files == 0:
      print mesdic['mes_err_key']
      sys.exit(2)

if null == 1:
   if action > 0:
      print mesdic['mes_err_key']
      sys.exit(2)

if exists == 1:
   if action > 0:
      print mesdic['mes_err_key']
      sys.exit(2)



if mnt == 1:
   os.system('mount ' + device + ' ' + mpoint + ' 2>/dev/null')



if help == 1:
   if locale != 'eng':
      try:
         file = open(path_locale + '/help.' + locale)

      except:
         print mesdic['mes_err_file'] + ' ' + path_locale + '/help.' + locale
         sys.exit(2)

      mes_help = ""
      for str_file in file:
         mes_help += str_file

      file.close()

   print mes_help

   sys.exit(0)



if fl_set_arch == 1:
   SetArch(set_arch, mesdic)
   sys.exit(0)



try:
   make_glob = open('/etc/make.globals')

except:
   print mesdic['mes_err_file'] + ' /etc/make.globals'
   sys.exit(2)

str_file = make_glob.readline()

path_distfiles = ""
while str_file != '':

   str_distr = str_file.strip()
   str_distr = str_distr[:8]

   if str_distr == 'DISTDIR=':
      str_file = str_file.split('=')
      path_distfiles = str_file[1].strip()

      break

   str_file = make_glob.readline()

make_glob.close()
make_glob = 0


if path_distfiles == '':
   print mesdic['mes_err_dist']
   sys.exit(2)

distfiles = path_distfiles.split(';');

for i in distfiles:

   if i.strip() != '':
      dist_path.append(i.strip())



keyw = 0
if fastkw == 1:
   keyw = 1
elif keywords == 1:
   keyw = 1


if keyw == 1:

   for pak in work_packages:
      
      if len(pak.split('/')) != 2:
         print mesdic['mes_err_ambiguity'] + ": " + pak

         sys.exit(2)

      
      if sign_kw != '-':
         if sign_kw != '*':
            if pkgsplit(pak) == None:
               print mesdic['mes_err_add_version'] + ": " + pak
               sys.exit(2)

      
      elif sign_kw == '-':
         if pkgsplit(pak) != None:
            print mesdic['mes_err_del_version'] + ": " + pak
            sys.exit(2)

   
   name_shab = re.compile('[\< | \> | \= | \- | \*]')

   if name_shab.findall(sign_kw[0]) == []:
      print mesdic['mes_err_sign']
      sys.exit(2)

   if len(sign_kw) == 2:

      if sign_kw[1] != '=': 
         print mesdic['mes_err_sign']
         sys.exit(2)

   if sign_kw == '-':
      sign_kw = ''

   
   if arch == '':
      print mesdic['mes_err_init_arch']
      sys.exit(2)
         
   for path_to_kw in path_keywords:

      
      if os.path.exists(path_to_kw) == False:
         try:
            os.system('touch ' + path_to_kw)
            print mesdic['mes_create_file'] + " " + path_to_kw
         except:
            print mesdic['mes_err_file_create'] + ' ' + path_to_kw
            sys.exit(2)

      
      write_paks = {}
      for pak in work_packages:
         write_paks[pak] = sign_kw + pak + ' ~' + arch

      
      is_kw = {}
      for pak in work_packages:
         is_kw[pak] = 0

      
      kw_set = {}
      for pak in work_packages:
         kw_set[pak] = 1

      
      box_k = []
      
      oldpak = {}



      
      try:
         pack_keyw = open(path_to_kw)

      except:
         print mesdic['mes_err_file'] + ' ' + path_to_kw
         sys.exit(2)

      
      
      for str_file in pack_keyw:
         str_nocom = str_file.split("#")
         str_nocom = str_nocom[0].strip()

         if str_nocom.strip() == "":
            box_k.append(str_file.replace('\n', ''))
            continue
         else:
            str_file = str_file.strip()

         
         neq_file = True
         num = -1
         str_file = str_file.replace('\t', ' ')
         for ch in str_file:
            num += 1
            if name_shab.findall(ch) != []:
               continue
            elif ch == ' ':
               continue
            break

         pak_str = ""
         chr = str_file[num]
         while chr != " ":
            pak_str += chr
            num += 1
            chr = str_file[num]

         
         for pak in work_packages:

            try:
               pak_str_nv = pkgsplit(pak_str)
               pak_str_nv = pak_str_nv[0]
            except:
               pak_str_nv = pak_str

            try:
               pak_nv = pkgsplit(pak)
               pak_nv = pak_nv[0]
            except:
               pak_nv = pak

            if pak_nv.strip() == pak_str_nv.strip():
               is_kw[pak] = 1
               oldpak[pak] = str_file.strip()
               neq_file = False
               break

         if neq_file:
            box_k.append(str_file.replace('\n', ''))

         # str_file = file_kw.readline()

      pack_keyw.close()
      pack_keyw = 0


      if fastkw == 1:
         # for kw in kw_set.keys():
         for kw in work_packages:
            if is_kw[kw] == 1:
               kw_set[kw] = 0
               sign_kw = ''
            else:
               kw_set[kw] = 1

      if sign_kw == '*':
         for kw in kw_set.keys():
            kw_set[kw] = 0

      else:
         for kw in kw_set.keys():
            if kw_set[kw] == 1:
               box_k.append(write_paks[kw])


      try:
         pack_keyw = open(path_to_kw, 'w')

      except:
         print mesdic['mes_err_file'] + ' ' + path_to_kw
         print mesdic['mes_err_root']
         sys.exit(2)

      for str in box_k:
         pack_keyw.write(str + '\n')

      pack_keyw.close()
      pack_keyw = 0


      while len(mesdic['mes_delete']) < 15:
         mesdic['mes_delete'] += ' '

      while len(mesdic['mes_set']) < 15:
         mesdic['mes_set'] += ' '


      is_space = False
      if len(work_packages) > 1:
         is_space = True


      is_title = False
      if len(path_keywords) > 1:
         if len(oldpak) > 0:
            is_title = True
         else:
            for kw in kw_set.keys():
               if kw_set[kw] == 1:
                  is_title = True


      if is_title:
         print SetColor("green", path_to_kw,iscolor) + ":"


      for pak in work_packages:

         if oldpak.has_key(pak):
            if oldpak[pak] != "":
               print SetColor("teal", mesdic['mes_delete'] ,iscolor) + "'" + oldpak[pak] + "'"

         if kw_set.has_key(pak):
            if kw_set[pak] == 1:
               print SetColor("turquoise", mesdic['mes_set'] ,iscolor) + "'" + write_paks[pak] + "'"

         if is_space:
            print "-----------------------------------------"




if mask == 1:

   for pak in work_packages:
      
      if len(pak.split('/')) != 2:
         print mesdic['mes_err_ambiguity'] + ": " + pak

         sys.exit(2)

      
      if sign_mask != '-':
         if sign_mask != '*':
            if pkgsplit(pak) == None:
               print mesdic['mes_err_add_version'] + ": " + pak
               sys.exit(2)

      
      elif sign_mask == '-':
         if pkgsplit(pak) != None:
            print mesdic['mes_err_del_version'] + ": " + pak
            sys.exit(2)

   
   name_shab = re.compile('[\< | \> | \= | \- | \*]')

   if name_shab.findall(sign_mask[0]) == []:
      print mesdic['mes_err_sign']
      sys.exit(2)

   if len(sign_mask) == 2:

      if sign_mask[1] != '=': 
         print mesdic['mes_err_sign']
         sys.exit(2)

   if sign_mask == '-':
      sign_mask = ''
        
   for path_to_mask in path_masks:

      
      if os.path.exists(path_to_mask) == 0:
         try:
            os.system('touch ' + path_to_mask)
            print mesdic['mes_create_file'] + " " + path_to_mask
         except:
            print mesdic['mes_err_file_create'] + ' ' + path_to_mask
            sys.exit(2)

      
      write_paks = {}
      for pak in work_packages:
         write_paks[pak] = sign_mask + pak

      
      is_mask = {}
      for pak in work_packages:
         is_mask[pak] = 0

      
      mask_set = {}
      for pak in work_packages:
         mask_set[pak] = 1

      
      box_k = []
      
      oldpak = {}



      
      try:
         pack_mask = open(path_to_mask)

      except:
         print mesdic['mes_err_file'] + ' ' + path_to_mask
         sys.exit(2)

      for str_file in pack_mask:
         str_nocom = str_file.split("#")
         str_nocom = str_nocom[0].strip()

         if str_nocom.strip() == "":
            box_k.append(str_file.replace('\n', ''))
            continue
         else:
            str_file = str_file.strip()

         neq_file = True
         str_file = str_file.strip()

         
         num = -1
         str_file = str_file.replace('\t', ' ')
         for ch in str_file:
            num += 1
            if name_shab.findall(ch) != []:
               continue
            elif ch == ' ':
               continue
            break

         pak_str = str_file[num:]

         
         for pak in work_packages:

            try:
               pak_str_nv = pkgsplit(pak_str)
               pak_str_nv = pak_str_nv[0]
            except:
               pak_str_nv = pak_str

            try:
               pak_nv = pkgsplit(pak)
               pak_nv = pak_nv[0]
            except:
               pak_nv = pak

            if pak_nv.strip() == pak_str_nv.strip():
               is_mask[pak] = 1
               oldpak[pak] = str_file.strip()
               neq_file = False
               break

         if neq_file:
            box_k.append(str_file.replace('\n', ''))

      pack_mask.close()    
      pack_mask = 0


      if sign_mask == '*':
         for kw in mask_set.keys():
            mask_set[kw] = 0

      else:
         for kw in mask_set.keys():
            if mask_set[kw] == 1:
               box_k.append(write_paks[kw])


      try:
         pack_mask = open(path_to_mask, 'w')

      except:
         print mesdic['mes_err_file'] + ' ' + path_to_mask
         print mesdic['mes_err_root']
         sys.exit(2)

      for str in box_k:
         pack_mask.write(str + '\n')

      pack_mask.close()      
      pack_mask = 0


      while len(mesdic['mes_delete']) < 15:
         mesdic['mes_delete'] += ' '

      while len(mesdic['mes_set']) < 15:
         mesdic['mes_set'] += ' '


      is_space = False
      if len(work_packages) > 1:
         is_space = True


      is_title = False
      if len(path_masks) > 1:
         if len(oldpak) > 0:
            is_title = True
         else:
            for kw in mask_set.keys():
               if mask_set[kw] == 1:
                  is_title = True


      if is_title:
         print SetColor("green", path_to_mask,iscolor) + ":"


      for pak in work_packages:

         if oldpak.has_key(pak):
            if oldpak[pak] != "":
               print SetColor("teal", mesdic['mes_delete'] ,iscolor) + "'" + oldpak[pak] + "'"

         if mask_set.has_key(pak):
            if mask_set[pak] == 1:
               print SetColor("turquoise", mesdic['mes_set'] ,iscolor) + "'" + write_paks[pak] + "'"

         if is_space:
            print "-----------------------------------------"




if uses == 1:

   for pak in work_packages:
      
      if len(pak.split('/')) != 2:
         print mesdic['mes_err_ambiguity']

         sys.exit(2)

      
      if pkgsplit(pak) != None:
         print mesdic['mes_err_del_version'] + ": " + pak
         sys.exit(2)

   for path_to_uses in path_uses:

      
      if os.path.exists(path_to_uses) == 0:
         try:
            os.system('touch ' + path_to_uses)
            print mesdic['mes_create_file'] + " " + path_to_uses
         except:
            print mesdic['mes_err_file_create'] + ' ' + path_to_uses
            sys.exit(2)

      try:
         pack_uses = open(path_to_uses)

      except:
         print mesdic['mes_err_file'] + ' ' + path_to_uses

         sys.exit(2)

      new_use = flags.split(' ')

      
      old_use_str = {}
      
      box_fl = []

      
      use_str = {}
      
      str_file = pack_uses.readline()

      
      while str_file != '':

         pak_str = str_file.strip()

         
         pak_str = pak_str.replace('\t', ' ')
         pak_str = pak_str.split()
         pak_str = pak_str[0]

         isn_pak = True

         
         for pak in work_packages:

            if pak.strip() == pak_str.strip():
               use_str[pak] = str_file
               str_file = pack_uses.readline()

               isn_pak = False

               break


         if isn_pak:
            box_fl += [str_file]
            str_file = pack_uses.readline()

      pack_uses.close()
      pack_uses = 0

      for pak in use_str.keys():
         old_use_str[pak] = use_str[pak].strip();


      
      use_upd = {}

      for pak in work_packages:

         if use_str.has_key(pak):

            
            use_str[pak] = use_str[pak].replace('\t', ' ')
            use_str[pak] = use_str[pak].replace('\n', ' ')
            use_str[pak] = use_str[pak].strip()      
            buff = use_str[pak].split(' ')

            
            old_use = []

            
            for i in buff:

               if i.find(pak) > -1:
                  pass

               elif i == '':
                  pass

               else:
                  old_use += [i]

            
            for i in new_use:

               if find(old_use, i) == 1:
                  old_use = delete(old_use, i)

               if i[0] != '*':
                  if use_upd.has_key(pak) == False:
                     use_upd[pak] = [i]
                  else:
                     use_upd[pak] += [i]

            for i in old_use:
               if use_upd.has_key(pak) == False:
                  use_upd[pak] = [i]
               else:
                  use_upd[pak] += [i]

         else:
            for i in new_use:

               if i[0] != '*':
                  if use_upd.has_key(pak) == False:
                     use_upd[pak] = [i]
                  else:
                     use_upd[pak] += [i]

   
      if flags != '-':

         try:
            pack_uses = open(path_to_uses, 'w')

         except:
            print mesdic['mes_err_file'] + ' ' + path_to_uses
            print mesdic['mes_err_root']

            sys.exit(2)

         if len(use_upd) > 0:
            for pak in work_packages:
               if use_str.has_key(pak):
                  use_str[pak] = pak + '        '
               elif use_upd.has_key(pak):
                  use_str[pak] = pak + '        '

            for pak in use_str.keys():
               if use_upd.has_key(pak):
                  for i in use_upd[pak]:
                     if i[0] == '-':
                        use_str[pak] += ' ' + i
                     else:
                        use_str[pak] += ' ' + i

            if flags != '*':
               for pak in use_str.keys():
                  pack_uses.write(use_str[pak] + '\n')

         else:
            use_str = ''

         for i in box_fl:
            pack_uses.write(i)

         pack_uses.close() 
         pack_uses = 0

   
      while len(mesdic['mes_delete']) < 15:
         mesdic['mes_delete'] += ' '

      while len(mesdic['mes_set']) < 15:
         mesdic['mes_set'] += ' '

   
      is_space = False
      if len(work_packages) > 1:
         is_space = True

   
      is_title = False
      if len(path_uses) > 1:
         if len(use_str) > 0:
            is_title = True
         elif len(old_use_str) > 0:
            is_title = True

   
      if is_title:
         print SetColor("green", path_to_uses,iscolor) + ":"

   

      for pak in work_packages:

         
         if len(old_use_str) > 0:
            if old_use_str.has_key(pak):
               print SetColor("teal", mesdic['mes_delete'] ,iscolor) + "'" + old_use_str[pak] + "'"

         
         if flags != '*':
            if len(use_str) > 0:
               if use_str.has_key(pak):
                  print SetColor("turquoise", mesdic['mes_set'] ,iscolor) + "'" + use_str[pak] + "'"

         if is_space:
            print "-----------------------------------------"




if print_uses == 1:

   
   tempf = tempfile.mktemp()
 

   box_uses_n = veb_use.split()
   box_uses = []

   for u in box_uses_n:
      u = u.replace("*", "")
      u = u.replace("(", "")
      u = u.replace(")", "")

      if u != '':
         if u[0] == '-':
            box_uses.append(u[1:])
         else:
            box_uses.append(u)
         

   is_use = 0
   for u in box_uses:
      is_use = 1
      os.system("cat /usr/portage/profiles/use.desc | grep '" + "\<" + u + "\>' >> " + tempf)

   
   box_out = {}

   for u in box_uses:
      if u != '':
         box_out[u] = '<unknown>'

   exist_use = {}

   for u in box_uses:
      if u != '':
         exist_use[u] = 0

   if is_use == 1:
      try:
         file_tmp = open(tempf)

      except:
         print mesdic['mes_err_file']

         sys.exit(2)

      
      str_file = file_tmp.readline()

      
      while str_file != '':

         for u in box_uses:

            use = find_desc(str_file, u)

            if use != []:
               box_out[use[0]] = use[1]
               exist_use[use[0]] = 1
               break

         str_file = file_tmp.readline()

      file_tmp.close()

   udesk = 0
   for u in exist_use.keys():
      if exist_use[u] == 0:
         udesk = 1

   if udesk == 1:

      
      tempf = tempfile.mktemp()

      for u in exist_use.keys():

         if exist_use[u] == 0:
            os.system("cat /usr/portage/profiles/use.local.desc | grep '" + "\<" + u + "\>' >> " + tempf)

      try:
         file_tmp = open(tempf)

      except:
         print mesdic['mes_err_file']

         sys.exit(2)

      
      str_file = file_tmp.readline()

      
      while str_file != '':

         for u in box_uses:

            if exist_use[u] == 0:
               use = find_local_desc(str_file, u)

               if use != []:
                  box_out[use[1] + '(' + use[0] + ')'] = use[2]
                  box_out[use[1]] = 'none'
                  break

         str_file = file_tmp.readline()

      file_tmp.close()


   use_out = []

   for u in box_out.keys():
      use_out.append(u.strip())

   use_out.sort()

   max_len = 0
   for u in box_out.keys():
      if max_len < len(u.strip()):
         max_len = len(u.strip())

   max_len += 1

   
   use_found  = []
   use_nfound = []
   for i in use_out:

      if box_out[i.strip()] != '<unknown>':
         use_found.append(i)
      else:
         use_nfound.append(i)

   
   is_use = 0
   first = 1
   for i in use_found:
      is_use = 1

      if first == 1:
         print
         first = 0

      
      while len(i) < max_len:
         i += ' '

      if box_out[i.strip()] != 'none':
         if color == 'true':
            if box_out[i.strip()] != '<unknown>':
               print '  ' + SetColor("yellow", i,iscolor) + ' : ' + box_out[i.strip()]
            else:
               print '  ' + i + ' : ' + box_out[i.strip()]
         else:
            print '  ' + i + ' : ' + box_out[i.strip()]


   
   first = 1
   for i in use_nfound:
      is_use = 1

      if first == 1:
         print
         first = 0

      
      while len(i) < max_len:
         i += ' '

      if box_out[i.strip()] != 'none':
         if color == 'true':
            if box_out[i.strip()] != '<unknown>':
               print '  ' + SetColor("yellow", i,iscolor) + ' : ' + box_out[i.strip()]
            else:
               print '  ' + i + ' : ' + box_out[i.strip()]
         else:
            print '  ' + i + ' : ' + box_out[i.strip()]

   print

   
   if is_use == 0:
      print mesdic['mes_no_uses']



if create_table == 1:

   if assoc != '':

      if is_title(title, path_base, mesdic) == 1:
         print mesdic['mes_err_title']

         sys.exit(2)

      name_file = 'table' + to_str(int(uniform(1, 1000000)))


      while is_file(name_file, path_base) == 1:

         name_file = 'table' + to_str(int(uniform(1, 1000000)))
         

      os.system('touch ' + path_base + '/' + name_file)

      try:
         file = open(path_base + '/' + name_file, 'w')
      except:
         print mesdic['mes_err_file'] + ' ' + path_base + '/' + name_file
         sys.exit(2)
      
      file.write('<title>' + title.strip() + '</title>\n')
      file.write('\n')

      try:
         for fle in os.listdir(assoc.strip()):
            file.write(fle + '\n')

      except:
         print mesdic['mes_err_assoc']
         file.close()
         os.system('rm ' + path_base + '/' + name_file)

         sys.exit(2)

      file.close()

      print mesdic['mes_create_table'] + " '" + title.strip() + "'"

   else:
      print mesdic['mes_err_assoc']

      sys.exit(2)



if add_table == 1:

   addtable = addtable.split(';')

   for table in addtable:

      nametab = table.rsplit('/', 1)
      dirtab  = nametab[0]
      nametab = nametab[1]

      if nametab == '*':

         for fle in os.listdir(dirtab):
         
            titl = GetTitle(dirtab + '/' + fle)

            if titl != '':

               if is_title(titl, path_base, mesdic) == 1:
                  print SetColor("yellow", titl,iscolor) + " : " + mesdic['mes_exits_table']
                  continue

               os.system('cp "' + dirtab + '/' + fle + '" "' + path_base + '/' + fle + '"')
               print mesdic['mes_add_table'] + " : " + SetColor("yellow", titl,iscolor)

      else:

         titl = GetTitle(table)

         if titl != '':

            if is_title(titl, path_base, mesdic) == 1:
               print SetColor("yellow", titl,iscolor) + " : " + mesdic['mes_exits_table']
               continue

            os.system('cp "' + table + '" "' + path_base + '/' + nametab + '"')
            print mesdic['mes_add_table'] + " : " + SetColor("yellow", titl,iscolor)

         else:
            print mesdic['mes_err_bad_table']



if list_tables == 1:

   
   if title == '*':
      tempf = tempfile.mktemp()

   for fle in os.listdir(path_base):

      try:
         file = open(path_base + '/' + fle)
      except:
         print mesdic['mes_err_file'] + ' ' + path_base + '/' + fle
         sys.exit(2)

      str = file.readline()

      file.close()

      
      titl = ''
      if str.find('<title>') > -1:
         str_title = str.split('<title>')

         if str_title[1].find('</title>') > -1:
            str_title = str_title[1].split('</title>')
            titl = str_title[0].strip()
   

      if titl != '':

         
         if title == '*':
            os.system("echo '" + titl + "' >> " + tempf)

         else:
            print  SetColor("yellow", titl,iscolor)



if delete_table == 1:

   aldel = 0

   if title.strip() == '*':

      try:
         file_d = open(tempf)
      except:        
         print mesdic['mes_err_file']
         sys.exit(2)

      
      str_file = file_d.readline()

      
      while str_file != '':

         for fle in os.listdir(path_base):

            try:
               file = open(path_base + '/' + fle)
            except:
               print mesdic['mes_err_file'] + ' ' + path_base + '/' + fle
               sys.exit(2)

            str = file.readline()

            file.close()

            
            titl = ''
            if str.find('<title>') > -1:
               str_title = str.split('<title>')

               if str_title[1].find('</title>') > -1:
                  str_title = str_title[1].split('</title>')
                  titl = str_title[0].strip()

            if titl == '':
               continue

            if titl.strip() == str_file.strip():
               os.system("rm '" + path_base + "/" + fle + "'")
               print mesdic['mes_err_del_table'] + " '" + str_file.strip() + "'"
               aldel = 1
               break

         str_file = file_d.readline()

      file_d.close()

   if aldel == 0:

      title = title.split(';')

      for table in title:

         for fle in os.listdir(path_base):

            try:
               file = open(path_base + '/' + fle)
            except:
               print mesdic['mes_err_file'] + ' ' + path_base + '/' + fle
               sys.exit(2)

            str = file.readline()

            file.close()

            
            titl = ''
            if str.find('<title>') > -1:
               str_title = str.split('<title>')

               if str_title[1].find('</title>') > -1:
                  str_title = str_title[1].split('</title>')
                  titl = str_title[0].strip()

            if titl == '':
               continue

            if titl.strip() == table.strip():
               os.system("rm '" + path_base + "/" + fle + "'")
               print mesdic['mes_err_del_table'] + " '" + table.strip() + "'"
               aldel = 1
               break

   if aldel == 0:
      print mesdic['mes_err_dont_ex_table']



if calc_dep == 1:
   
   
   box_dep = []

   packages = ""
   world = False
   system = False
   eworld = False
   esystem = False
   preserved_rebuild = False
   revdep_rebuild = False

   for wpak in work_packages:
      if wpak.strip() == "world":
         world = True
         continue

      if wpak.strip() == "system":
         system = True
         continue

      if wpak.strip() == "eworld":
         eworld = True
         continue

      if wpak.strip() == "esystem":
         esystem = True
         continue

      if wpak.strip() == "preserved-rebuild":
         preserved_rebuild = True
         continue

      if wpak.strip() == "revdep-rebuild":
         revdep_rebuild = True
         continue

      packages += (" " + wpak)

   
   tempf = tempfile.mktemp()

   if world:
      os.system('emerge -fp --update --deep --newuse world  >> ' + tempf)

   if system:
      os.system('emerge -fp --update --deep --newuse system  >> ' + tempf)

   if eworld:
      os.system('emerge -fpe world  >> ' + tempf)

   if esystem:
      os.system('emerge -fpe system  >> ' + tempf)

   if preserved_rebuild:
      os.system('emerge -fp @preserved-rebuild  >> ' + tempf)

   if revdep_rebuild:
      try:
         file = open("/var/cache/revdep-rebuild/4_ebuilds.rr")
      except:
         print mesdic['mes_err_file'] + " /var/cache/revdep-rebuild/4_ebuilds.rr"
         sys.exit(2)
         
   
      str = file.readline()
      while str != '':
         pkg = str.split(':')
         os.system('emerge -fp ' + pkg[0] + '  >> ' + tempf)
         str = file.readline()
      

   if packages != "":
      os.system('emerge -fp ' + packages + ' >> ' + tempf)

   try:
      file = open(tempf)
   except:
      print mesdic['mes_err_file'] + " tempf"
      sys.exit(2)

   
   str = file.readline()

   
   while str != '':

      while str == '':
         str = file.readline()

      if str.count('emerge: there are no ebuilds to satisfy') != 0:
         str = str.split('emerge: ')
         str = str[1].replace(".\n", "")
         print 'T' + str[1:]

      else:

         protokol = str.split(':', 1)
         hf_shab1 = re.compile('^http')
         hf_shab2 = re.compile('^ftp')

         if hf_shab1.findall(protokol[0]) != []:
            list_str = str.split()
            protokol = list_str[0].rsplit('/', 1)
            box_dep += [protokol[1].replace('\n', '').strip()]

         if hf_shab2.findall(protokol[0]) != []:
            list_str = str.split()
            protokol = list_str[0].rsplit('/', 1)
            box_dep += [protokol[1].replace('\n', '').strip()]

            # protokol = str.rsplit('/', 1)
            # box_dep += [protokol[1].replace('\n', '').strip()]

      str = file.readline()
      
   file.close()


   temp_dic = {}
   for fil in box_dep:
      if temp_dic.has_key(fil.strip()):
         continue
      temp_dic[fil.strip()] = 0

   box_dep = []

   for fil in temp_dic.keys():
      box_dep.append(fil)


   box_dep.sort()



   
   box_for_getdelta = {}

   
   is_file = {}

   
   file_exist = {}

   
   for file in box_dep:

      if is_file.has_key(file) == 0:
         is_file[file] = isnt_file_sign
         box_for_getdelta[file] = 0

   
   for file in is_file.keys():

      file_exist[file] = ['<unknown>']
      next_file = False

      for path in dist_path:

         if path.strip() != '':

            try:
               if VSearch(file, path, True, mesdic):

                  is_file[file] = is_file_sign
                  box_for_getdelta[file] = 1
                  next_file = True

            except:
               print mesdic['mes_err_dist_config']

               sys.exit(2)

         if next_file:
            break



   for fil in is_file.keys():

      for table in os.listdir(path_base):

         try:
            file = open(path_base + '/' + table)
         except:
            print mesdic['mes_err_file'] + ' ' + table
            sys.exit(2)

         
         str = file.readline()

         
         titl = ''
         if str.find('<title>') > -1:
            str_title = str.split('<title>')

            if str_title[1].find('</title>') > -1:
               str_title = str_title[1].split('</title>')
               titl = str_title[0].strip()

         if titl == '':
            continue

         file.close()

         if VSearch(fil, path_base + '/' + table, False, mesdic):

            if len(file_exist[fil]) == 1:
               if file_exist[fil][0] == '<unknown>':
                  file_exist[fil] = [titl]
               else:
                  file_exist[fil] += [titl]
            else:
               file_exist[fil] += [titl]

   
   dict_medium = {}

   for fil in file_exist.keys():

      for dev in file_exist[fil]:

         if dict_medium.has_key(dev) == False:

            if dev != '<unknown>':

               if is_file[fil] == is_file_sign:
                  dict_medium[dev] = 1
               else:
                  dict_medium[dev] = 0

               if box_for_getdelta[fil] == 0:

                  box_for_getdelta[fil] == 1



   if copy_files == 1:

      
      if files_path == []:
         print mes_err_file

         sys.exit(2)

      # path_files = path_files.split(';');

      target = dist_path[0]

      
      for fil in is_file.keys():

         if is_file[fil] == isnt_file_sign:

            for fil_ex in file_exist[fil]:

               dict_medium[fil_ex] = 0

               for path in files_path:

                  if path.strip() != '':

                     try:

                        if os.path.exists(path) == 0:
                           raise MyError

                        if VSearch(fil, path, True, mesdic):
                           is_file[fil] = is_file_sign
                           dict_medium[fil_ex] = 1
                           os.system('\cp -v ' + path.strip() + '/' + fil + ' ' + target)

                           break            

                     except MyError:
                        pass


   str_abs_medium  = ''
   dic_abs_medium = {}

   for fil in is_file.keys():

      if is_file[fil] == isnt_file_sign:

         for fil_ex in file_exist[fil]:

            if fil_ex != '<unknown>':
               if dic_abs_medium.has_key(fil_ex):
                  pass
               else:
                  str_abs_medium += '  ' + fil_ex
                  dic_abs_medium[fil_ex] = 'null'

   if copy_files == 1:

      if str_abs_medium != '':
         print_str = '\n' + SetColor("green", mesdic['mes_mediums_program'], iscolor)
         print_str += SetColor("turquoise", str_abs_medium,iscolor)
         print print_str



   if getdelta == 1:

      for fil in box_for_getdelta.keys():

         if box_for_getdelta[fil] == 0:

            if os.system('/usr/bin/getdelta.sh ' + fil) != 0:

               print mesdic['mes_err_inst_getdelta']
               break
     



if out_dep == 1:

   
   len_space = 0
   for dep in box_dep:
      if len(dep) > len_space:
         len_space = len(dep)

   if len(is_file_sign) > len(isnt_file_sign):
      len_space += len(is_file_sign)
   else:
      len_space += len(isnt_file_sign)
   
   len_space += 3

   out_ex_dev = False

   files_ex = 0
   files_ab = 0
   is_templ = 0

   for dep in box_dep:

      
      str_dep = dep

      
      is_templ = left
      if is_templ == 0:
         is_templ = right

      if is_templ == 0:
         if simple == 0:
            out_ex_dev = True

         
         while len(str_dep) <= len_space:
            str_dep += " "

         
         if ex_flag == 1:
            if is_file[dep] == is_file_sign:
               str_dep = " " + is_file[dep] + " " + SetColor("red", str_dep, iscolor)
               files_ex += 1
            elif is_file[dep] == isnt_file_sign:
               str_dep = " " + is_file[dep] + " " + SetColor("blue", str_dep, iscolor)
               files_ab += 1

         
         if pl_flag == 1:
            
            str_exist = ""
            isnt_unknown = True
            if len(file_exist[dep]) == 1:
               if file_exist[dep][0] == '<unknown>':
                  str_exist = "  " + SetColor("teal", file_exist[dep][0], iscolor)
                  isnt_unknown = False

            if isnt_unknown:
               for dev in file_exist[dep]:
                  str_exist += ("  " + SetColor("turquoise", dev, iscolor))

            str_dep = str_dep + ":" + str_exist

      else:
         str_dep = pref + str_dep + post

      
      is_filtr = null
      if is_filtr == 0:
         is_filtr = exists

      if is_filtr == 1:
         if null == 1:
            if is_file[dep] == isnt_file_sign:
               print str_dep

         if exists == 1:
            if is_file[dep] == is_file_sign:
               print str_dep

      else:
         print str_dep

   if is_templ == 0:
      if ex_flag == 1:
         if info_flag == 1:
            str_info  = SetColor("green", mesdic['mes_all'], iscolor) + " %s " %len(box_dep) + mesdic['mes_files']
            str_info += "  "
            str_info += SetColor("green", mesdic['mes_ex'],  iscolor) + " %s " %files_ex + mesdic['mes_files']
            str_info += "  "
            str_info += SetColor("green", mesdic['mes_ab'],  iscolor) + " %s " %files_ab + mesdic['mes_files']

            print str_info

   if out_ex_dev:
      str_medium = ""
      out_mes_medium = False

      if is_filtr == 1:
         if exists == 1:
            
            for dev in dict_medium:
               if dic_abs_medium.has_key(dev):
                  pass
               else:
                  str_medium +=  "  +" + SetColor("turquoise", dev, iscolor)
                  out_mes_medium = True

         if null == 1:
            
            for dev in dict_medium:
               if dic_abs_medium.has_key(dev):
                  str_medium +=  "  -" + SetColor("teal", dev, iscolor)
                  out_mes_medium = True

      else:

         
         for dev in dict_medium:
            if dic_abs_medium.has_key(dev):
               pass
            else:
               str_medium +=  "  +" + SetColor("turquoise", dev, iscolor)
               out_mes_medium = True

         
         for dev in dict_medium:
            if dic_abs_medium.has_key(dev):
               str_medium +=  "  -" + SetColor("teal", dev, iscolor)
               out_mes_medium = True

      if out_mes_medium:
         print SetColor("green", mesdic['mes_mediums'], iscolor) + str_medium



if mnt == 1:
   os.system('umount ' + device)
